package vn.com.unit.springmvc.repo;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import vn.com.unit.springmvc.domain.Vendor;

@Repository
@Transactional
public class VendorDaoImpl implements VendorDao
{
    @Autowired
    private EntityManager em;

    public Vendor findById(Long id)
    {
        return em.find(Vendor.class, id);
    }
    
    public Vendor findByCode(String code)
    {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Vendor> criteria = builder.createQuery(Vendor.class);
        Root<Vendor> vendor = criteria.from(Vendor.class);
        criteria.select(vendor).where(builder.equal(vendor.get("code"), code));
        TypedQuery<Vendor> query  = em.createQuery(criteria);
        if(query == null || query.getFirstResult() == 0) {
        	return null;
        }
        return query.getSingleResult();
    }

    public Vendor findByName(String name)
    {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Vendor> criteria = builder.createQuery(Vendor.class);
        Root<Vendor> vendor = criteria.from(Vendor.class);
        criteria.select(vendor).where(builder.equal(vendor.get("name"), name));
        TypedQuery<Vendor> query  = em.createQuery(criteria);
        if(query == null || query.getFirstResult() == 0) {
        	return null;
        }
        return query.getSingleResult();
    }

    public List<Vendor> findAllOrderedByName()
    {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Vendor> criteria = cb.createQuery(Vendor.class);
        Root<Vendor> vendor = criteria.from(Vendor.class);
        criteria.select(vendor).orderBy(cb.asc(vendor.get("name")));
        return em.createQuery(criteria).getResultList();
    }

    public void register(Vendor vendor)
    {
        em.persist(vendor);
        return;
    }
    
    public void update(Vendor vendor)
    {
        em.merge(vendor);
        return;
    }
    
    public void delete(Long id)
    {
    	Vendor a  =  findById(id);
    	em.remove(a);
    	return;
    }
}
